<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>利宝公众号工具</title>
</head>
<script>
  const baseUrl = 'https://cs.libao.cn'
  // const baseUrl = 'https://lbone-uat11.libertymutual.com.cn'

  const onePlusShortApi = `${baseUrl}/platform/openapi/createshort`
  const maTransferUrl = `${baseUrl}/sticsale/html/matransfer.html`
  //https://cs.libao.cn/sticsale/platform/#/sticsale/paas/pushRecord?url=https%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMjM5MDYzNDA2MQ%3D%3D%26mid%3D2447503757%26idx%3D1%26sn%3D2403c508a75bac22a7ecbff9add412c6%26chksm%3Db25488af852301b9b2d1b34ae9af598e1fa43841561eb69b4139be2ba6f48542512b93b1366a%26token%3D1026631768%26lang%3Dzh_CN%23rd&sourceType=RW_LUCK
  const pushRecordUrl = `${baseUrl}/sticsale/platform/#/sticsale/paas/pushRecord`

  const getPushRecordUrl = (url, sourceType = 'shortAddressTool') => {
    return `${pushRecordUrl}?url=${encodeURIComponent(url)}&sourceType=${sourceType}`
  }

  function getQueryVariable (variable) {
    let query = window.location.search.substring(1)
    let vars = query.split('&')
    for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split('=')
      if (pair[0] === variable) {
        return decodeURIComponent(pair[1])
      }
    }
    return false
  }

  /**
   * 格式化参数
   * @param data
   * @return {string}
   */
  function formatParams (data, isPer = true) {
    var arr = []
    for (var name_1 in data) {
      // encodeURIComponent() ：用于对 URI 中的某一部分进行编码
      arr.push(encodeURIComponent(name_1) + '=' + encodeURIComponent(data[name_1]))
    }
    // 添加一个随机数参数，防止缓存
    // arr.push('v=' + random())

    var url = arr.join('&')
    return isPer ? '?' + url : url
  }

  /**
   * 获取随机数
   * @return {number}
   */
  function random () {
    return Math.floor(Math.random() * 10000 + 500)
  }

  /**
   * 网络请求
   * @type {{get(*, *=): *}}
   */
  const HttpUtil = (url, params = {}, method = 'POST') => {
    return new Promise((resolve, reject) => {
      let xhr = null
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
      } else { // IE6及其以下版本
        xhr = new ActiveXObjcet('Microsoft.XMLHTTP')
      }
      // 监听事件，只要 readyState 的值变化，就会调用 readystatechange 事件
      xhr.onreadystatechange = function () {
        // readyState属性表示请求/响应过程的当前活动阶段，4为完成，已经接收到全部响应数据
        if (xhr.readyState === 4) {
          const status = xhr.status
          if (status >= 200 && status < 300) { // status：响应的HTTP状态码，以2开头的都是成功
            let response = JSON.parse(xhr.responseText) //JSON响应

            if (response && response.resCode === '0') {
              resolve(response)
            } else {
              reject(response.message)
            }
          } else {
            reject('网络错误')
          }
        }
      }

      //GET请求 把参数放到url
      if (method.toLocaleUpperCase() === 'GET') {
        url += formatParams(params)
      }

      xhr.open(method.toLocaleUpperCase(), url, true) // 最后一个参数改为false为同步请求
      //必须，设置提交时的内容类型
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
      // 传输数据
      xhr.send(JSON.stringify(params))
    })

  }

  const setResult = (result) => {
    document.getElementById('result').value = result
  }

  const copyResult = () => {
    let resultEl = document.getElementById('result')
    resultEl.select()
    if (document.execCommand('copy')) {
      alert('复制到剪贴板成功')
    }
  }

  const buildMiniAppShortUrl = () => {
    let url = document.getElementById('url').value
    let sourceType = document.getElementById('sourceType').value

    url = url.replace(/^\s+|\s+$/g, '')
    if (!url) {
      alert('请输入地址')
      return
    }
    if (sourceType) {
      sourceType = sourceType.replace(/^\s+|\s+$/g, '')
    }

    let buildUrl

    if (!sourceType) {
      //不统计
      buildUrl = `${maTransferUrl}?query=${encodeURIComponent(url)}`
    } else {
      //统计神策
      buildUrl = `${maTransferUrl}?query=${encodeURIComponent(getPushRecordUrl(url, sourceType))}`
    }

    let
      params = {
        type: 'get',
        url: buildUrl,
      }
    HttpUtil(onePlusShortApi, params).then(res => {
      setResult(res.shorturl)
    }).catch(err => {
      alert(err)
    })

  }

  const copyPushResult = () => {
    let resultEl = document.getElementById('pushResult')
    resultEl.select()
    if (document.execCommand('copy')) {
      alert('复制到剪贴板成功')
    }
  }
  const buildPushUrl = () => {
    let url = document.getElementById('pushUrl').value
    let sourceType = document.getElementById('pushSourceType').value

    url = url.replace(/^\s+|\s+$/g, '')
    if (!url) {
      alert('请输入地址')
      return
    }
    if (sourceType) {
      sourceType = sourceType.replace(/^\s+|\s+$/g, '')
    }

    let pushResult = getPushRecordUrl(url, sourceType)
    document.getElementById('pushResult').value = pushResult
  }

  const copyShortResult = () => {
    let resultEl = document.getElementById('shortResult')
    resultEl.select()
    if (document.execCommand('copy')) {
      alert('复制到剪贴板成功')
    }
  }

  const buildShortUrl = () => {
    let url = document.getElementById('longUrl').value

    url = url.replace(/^\s+|\s+$/g, '')
    if (!url) {
      alert('请输入地址')
      return
    }

    let
      params = {
        type: 'get',
        url: url,
      }
    HttpUtil(onePlusShortApi, params).then(res => {

      document.getElementById('shortResult').value = res.shorturl
    }).catch(err => {
      alert(err)
    })

  }


</script>
<style>
    .hub {
        padding: 40px 80px;
        border-bottom: 1px black dashed;
    }

    input {
        padding: 8px 16px;
        width: 100%;
        margin-bottom: 20px;
    }

    button {
        padding: 4px 8px;
        margin-bottom: 20px;
    }

</style>
<body>

<div class="hub">
    <h2>利小宝短链接</h2>
    <input id="url" placeholder="目标地址">
    <input id="sourceType" placeholder="神策统计来源，不填不统计">
    <button onclick="buildMiniAppShortUrl()">生成小程序链接</button>

    <br>
    <br>
    <input id="result" placeholder="小程序链接">
    <button onclick="copyResult()">复制结果</button>
</div>

<div class="hub">
    <h2>推送消息网页统计</h2>
    <input id="pushUrl" placeholder="目标地址">
    <input id="pushSourceType" placeholder="神策统计来源，不填不统计">
    <button onclick="buildPushUrl()">生成统计链接</button>

    <br>
    <br>
    <input id="pushResult" placeholder="结果">
    <button onclick="copyPushResult()">复制统计链接</button>
</div>

<div class="hub">
    <h2>万家短链</h2>
    <input id="longUrl" placeholder="长链">
    <button onclick="buildShortUrl()">生成短链</button>

    <br>
    <br>
    <input id="shortResult" placeholder="结果">
    <button onclick="copyShortResult()">复制统计链接</button>
</div>

</body>
</html>
